/**
 * 
 */
package dp.passed;

/**
 * @author Michael
 * Given two words word1 and word2, find the minimum number of steps required to 
 * convert word1 to word2. (each operation is counted as 1 step.)
 * You have the following 3 operations permitted on a word:
 * a) Insert a character
 * b) Delete a character
 * c) Replace a character
 */
public class EditDistance {

	// d[i][j]: edit distance for word1.substring(0,i) and word2.substring(0,j)
	// d[i][j] = d[i-1][j-1] if same character
	// d[i][j] = min(d[i-1][j],d[i][j-1],d[i-1][j-1])+1 otherwise
	// answer: d[word1.length()][word2.length()]

	public static int minDistanceDP(String word1, String word2) {
		return minDistance(word1.toCharArray(), word2.toCharArray());
	}

	public static int minDistance(char[] word1, char[] word2) {
		int[][] d = new int[word1.length + 1][word2.length + 1];
		for (int i = 0; i <= word1.length; ++i) {
			d[i][0] = i;
		}
		for (int i = 0; i <= word2.length; ++i) {
			d[0][i] = i;
		}

		for (int i = 1; i <= word1.length; ++i) {
			for (int j = 1; j <= word2.length; ++j) {
				if (word1[i - 1] == word2[j - 1]) {
					d[i][j] = d[i - 1][j - 1];
				} else {
					d[i][j] = 1 + Math.min(Math.min(d[i][j - 1], d[i - 1][j]),
							d[i - 1][j - 1]);
				}
			}
		}
		return d[word1.length][word2.length];
	}

	public int minDistance(String word1, String word2) {
		if (word1.isEmpty())
			return word2.length();

		if (word2.isEmpty())
			return word1.length();

		int[][] dp = new int[word1.length() + 1][word2.length() + 1];

		for (int i = 0; i <= word1.length(); i++) {
			dp[i][0] = i;
		}
		for (int i = 0; i <= word2.length(); i++) {
			dp[0][i] = i;
		}

		for (int i1 = 1; i1 <= word1.length(); i1++) {
			for (int i2 = 1; i2 <= word2.length(); i2++) {
				if (word1.charAt(i1 - 1) == word2.charAt(i2 - 1)) {
					dp[i1][i2] = dp[i1 - 1][i2 - 1];
				} else {
					dp[i1][i2] = Math.min(dp[i1 - 1][i2 - 1],
							Math.min(dp[i1][i2 - 1], dp[i1 - 1][i2])) + 1;
				}

			}
		}

		return dp[word1.length()][word2.length()];
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(minDistanceDP("abc", "bcd"));
	}

	/**
	 * 
	 */
	public EditDistance() {
		System.out.println(minDistance("abc", "bcd"));
	}
}
